package srv

import (
	dbModel "back/entity/model"
	"back/entity/nailEntity"
	"back/entity/nailRepo"
	requset "back/router/request"
	"github.com/redis/go-redis/v9"
	"gorm.io/gen"
	"utilx/dbx/cache"
)

type NailMember struct {
	Repo   nailRepo.NailRepo
	bucket cache.RedisBucket
	redis  *redis.Client
}

func NewMember(repo nailRepo.NailRepo, bucket cache.RedisBucket) NailMember {
	client := bucket.GetClient(1)
	return NailMember{repo, bucket, client}
}
func (c NailMember) CacheSearchById(force bool, id int64) (any, error) {
	return cache.GetAop[nailEntity.NailMember](force, c.redis, dbModel.RedisKey(dbModel.TypeMember, id), func() (any, error) {
		return c.SearchById(id)
	})
}
func (c NailMember) CacheSearchBy(force bool, rec requset.SearchWithPage[nailEntity.NailMember]) (any, error) {
	return cache.GetAop[requset.PageResult[nailEntity.NailMember]](force, c.redis, dbModel.RedisKey(dbModel.TypeMember, rec), func() (any, error) {
		return c.SearchBy(rec)
	})

}

func (c NailMember) SearchById(id int64) (*nailEntity.NailMember, error) {

	return c.Repo.NailMember.Where(nailRepo.NailMember.ID.Eq(id)).First()
}
func (c NailMember) SearchBy(rec requset.SearchWithPage[nailEntity.NailMember]) (requset.PageResult[nailEntity.NailMember], error) {
	do := c.Repo.NailMember.Debug()
	do = do.Where(nailRepo.NailMember.Name.Like("%" + rec.Data.Name + "%"))
	byPage, i, err := do.FindByPage(int(rec.PageInfo.PageSize)*int(rec.PageInfo.Page-1), int(rec.PageInfo.PageSize))
	return requset.PageResult[nailEntity.NailMember]{
		Items: byPage,
		Total: i,
	}, err
}
func (c NailMember) DelById(id int64) (gen.ResultInfo, error) {

	return c.Repo.NailMember.Where(nailRepo.NailMember.ID.Eq(id)).Delete()
}
func (c NailMember) UpdateById(rec nailEntity.NailMember) error {

	return c.Repo.NailMember.Where(nailRepo.NailMember.ID.Eq(rec.ID)).Save(&rec)
}
func (c NailMember) UpdateBy(rec requset.UpdateBy[nailEntity.NailMember, nailEntity.NailMember]) error {
	return c.Repo.NailMember.Where(nailRepo.NailMember.ID.Eq(rec.Where.ID)).Save(&rec.Target)
}
func (c NailMember) Create(rec nailEntity.NailMember) error {
	return c.Repo.NailMember.Create(&rec)
}
